package cn.doctor.assistant.pad.base;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

import java.io.UnsupportedEncodingException;

import cn.doctor.assistant.pad.api.AssistAPI;

/**
 * Created by jiaolf on 2016/3/24.
 */
public class AssJsonRequest extends JsonRequest<String> {

    public AssJsonRequest(int method, String url, String requestBody,
                          Response.Listener<String> listener, Response.ErrorListener errorListener){
        super(method, url, requestBody, listener, errorListener);
    }

    /**
     * 使用默认为POST，域名为AssistAPI.URL_DOMAIN的请求
     * @param requestBody
     * @param listener
     * @param errorListener
     */
    public AssJsonRequest(String requestBody, Response.Listener<String> listener, Response.ErrorListener errorListener){
        this(Method.POST, AssistAPI.URL_DOMAIN, requestBody, listener, errorListener);
    }

    /**
     * 使用默认为POST，域名为AssistAPI.URL_DOMAIN的请求, 并使用默认的网络错误处理
     * @param requestBody
     * @param listener
     */
    public AssJsonRequest(String requestBody, Response.Listener<String> listener){
        this(Method.POST, AssistAPI.URL_DOMAIN, requestBody, listener, ErrorHandler.getErrorListener());
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }
}
